package com.qy.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qy.service.WxService;
import com.qy.utils.HttpUtils;

@WebServlet("/getQrCode")
public class QrCodeServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码格式,不然中文会乱码
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		//发送post请求获取ticket,页面通过ticket就可以展示二维码图片了
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
		url = url.replace("TOKEN", WxService.getAccessToken());
		/*600表示10分钟有效  scene_str是一个唯一标识,类似点击事件的key QR_STR_SCENE表示为临时二维码
		 * {
				"expire_seconds": 600, 
				"action_name": "QR_STR_SCENE", 
				"action_info": {
					"scene": {
						"scene_str": "test"
						
					}
				}
			}
		 */
		String jsonStr = "{\r\n" + 
				"	\"expire_seconds\": 600, \r\n" + 
				"	\"action_name\": \"QR_STR_SCENE\", \r\n" + 
				"	\"action_info\": {\r\n" + 
				"		\"scene\": {\r\n" + 
				"			\"scene_str\": \"test\"\r\n" + 
				"			\r\n" + 
				"		}\r\n" + 
				"	}\r\n" + 
				"}";
		String string = HttpUtils.sendPost(url, jsonStr);
		JSONObject object = JSONObject.parseObject(string);
		//将响应结果返回页面,用于显示二维码
		resp.getWriter().write(string);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}
}
